# -*- coding:utf-8 -*-

import croniter, datetime
import catAPI
from utils import ConfigUtil
import json


ymdhms = "%Y-%m-%d %H:%M:%S"

configName = "music.json"

# 入口方法
def alarm(robot, towxid, atwxid, atname, msg):
    # msg = "提醒#添加|0/1 * * * *|内容提醒"
    params = msg.split('|')
    if "提醒#添加" in msg:
        rstr = addAlarm(robot,towxid, atwxid, atname,params[1],params[2],1)
        sendmsg(robot,towxid,atwxid,atname,rstr)
        pass
    elif "提醒#停用" in msg:
        rstr = deleteAlarm(towxid, atwxid, params[1])
        sendmsg(robot,towxid,atwxid,atname,rstr)
        pass
    elif "提醒#全删" in msg:
        rstr = deleteAlarmAll(towxid, atwxid)
        sendmsg(robot,towxid,atwxid,atname,rstr)
        pass
    elif "提醒#列表" in msg:
        rstr =  listmy(towxid, atwxid)
        sendmsg(robot,towxid,atwxid,atname,rstr)
    else:
        rstr = "提醒格式如下\n提醒#[添加/列表/停用/全删 \n" \
               "举例：\n提醒#添加|0/1 * * * *|内容提醒\n" \
               "提醒#停用|0/1 * * * *\n" \
               "提醒#全删\n" \
               "提醒#列表\n" \
               ""
        sendmsg(robot,towxid,atwxid,atname,rstr)
    pass


# 添加提醒
def addAlarm(robot, towxid, atwxid, atname, time, note, state=0):
    try:
        data = dict()
        # at的微信id
        data['robot'] = robot
        data['towxid'] = towxid
        data['atwxid'] = atwxid
        data['atname'] = atname
        data['time'] = time
        data['note'] = note
        data['state'] = state
        loads = json.loads(ConfigUtil.readConfigJson(configName))
        if(loads.get("alist") == None):
            listData = [data]
            loads["alist"] = listData
        else:
            loads["alist"].append(data)
        ConfigUtil.writeConfigJson(configName, json.dumps(loads) )
        lr =getnear3(time)
        return "提醒设定成功！\n最近三次提醒时间：\n" + ("\n".join(lr))
    except Exception as e:
        print(e)

def getnear3(time):
    now = datetime.datetime.now()
    cron = croniter.croniter(time, now)
    lr = [cron.get_next(datetime.datetime).strftime("%Y-%m-%d %H:%M") for i in range(3)]
    return lr

def deleteAlarm(towxid, atwxid, time):
    try:
        print("删除提醒")
        jsonstr = ConfigUtil.readConfigJson(configName)
        loads = json.loads(jsonstr)
        list = loads.get("alist")
        listindex = []
        for data in list:
            if (data['towxid'] == towxid
                    and data['atwxid'] == atwxid
                    and data['time'] ==time):
                listindex.append(list.index(data))
        for ii in listindex:
            del list[ii]
        loads["alist"] = list
        ConfigUtil.writeConfigJson(configName, json.dumps(loads) )
        return "删除成功"
    except Exception as e:
        print(e)
    return "没有指定提醒"
def deleteAlarmAll(towxid, atwxid):
    jsonstr = ConfigUtil.readConfigJson(configName)
    loads = json.loads(jsonstr)
    list = loads.get("alist")
    listindex = []
    for data in list:
        if (data['towxid'] == towxid
                and data['atwxid'] == atwxid):
            listindex.append(list.index(data))
    for i in listindex:
        del list[i]
    loads["alist"] = list
    ConfigUtil.writeConfigJson(configName, json.dumps(loads) )
    return "删除成功"

def listmy(towxid, atwxid):
    jsonstr = ConfigUtil.readConfigJson(configName)
    loads = json.loads(jsonstr)
    if(len(loads.get("alist")) != 0):
        rstr = "你的提醒如下：\n"
        for data in loads.get("alist"):
            if (data['towxid'] == towxid and data['atwxid'] == atwxid):
                rstr += "|"+ data['time'] +"|"+ data['note'] +"\n"
        return rstr
    return "你没有提醒哦！"




# 一秒钟执行一次
def mainfun():
    jsonstr = ConfigUtil.readConfigJson(configName)
    loads = json.loads(jsonstr)
    if(loads.get("alist") == None):
        return
    for data in loads.get("alist"):
        now = datetime.datetime.now()
        if (data['state'] == 0):
            continue
        cron = croniter.croniter(data['time'], now)
        next = cron.get_next(datetime.datetime)
        delta = next - now
        if (delta.seconds == 1):
            print("发送提醒")
            lr =getnear3(data["time"])
            notenr = "" + data['note'] +"\n预定提醒时间:" + next.strftime(ymdhms) +  \
                     "\n近三次提醒时间：\n"+("\n".join(lr))
            sendmsg(data['robot'], data['towxid'], data['atwxid'], data['atname'], notenr)
            #del listData[listData.index(data)]

        pass

def sendmsg(robot,towxid,atwxid,atname,notenr):
    print(notenr)
    catAPI.send_group_at_msg(robot,towxid,atwxid,atname,notenr)


def CronRunNextTimelist(sched, frequency=1):
    now = datetime.datetime.now()
    cron = croniter.croniter(sched, now)
    nowstr = now.strftime(ymdhms)
    # nowstr = "2022-11-09 08:00:00"
    next = cron.get_next(datetime.datetime)
    nextstr = next.strftime(ymdhms)
    print(nowstr)
    print(nextstr)
    print(nowstr == nextstr)
    delta = next - now
    print(delta)
    print(delta.seconds)
    print(delta.seconds < 10)

    print(cron.get_prev(datetime.datetime))
    print()
    return [cron.get_next(datetime.datetime).strftime("%Y-%m-%d %H:%M") for i in range(frequency)]


if __name__ == '__main__':
    print("wo shi alarm")
    sched = "0/1 * * * *"
    # print(CronRunNextTimelist(sched,frequency=3))
    # print(addAlarm("aa","aa","aa","aa",sched,"提醒我",1))
    print(addAlarm("aa","aa1","aa","aa",sched,"提醒我",1))

    # mainfun()

    print(listmy("aa","aa"))

    print(deleteAlarm("aa1","aa",sched))
    print(listmy("aa","aa"))